<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Usersauthority;
use App\Models\Miniappsauthorization;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use App\Models\Linkslistsminapps;
use App\Models\Linkslists;
use App\Models\Users;
use App\Services\CacheService;
use App\Services\WechatopenService;
use App\Services\WechatsService;
use App\Services\WechatoffiaccountService;
use App\Services\WechattmplmsgService;
use App\Jobs\Miniappdisable;
use DB,Log,Exception;

class Pubminivisitstatus extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'miniapps:publicvisitstatus';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '每分钟检测公用小程序服务状态（是否暂停服务）';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->unAuthorAppids = [];
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // miniapp_type 小程序类型:1.三方上架2.用户自有3.API获取Token4.扫码授权
        // visitstatus 上线状态:1.正常2.暂停服务3.程序异常4.封禁5.未检测
        DB::table("links_lists_minapps")->select('id','users_id','appid','name','miniapp_type','type')->whereIn('miniapp_type',[1,2,4])->where([['visitstatus','=',1],['status','=',2],['disable','=',3]])->groupBy('appid')->orderBy('id','ASC')->chunk(100, function($miniapps) {
            $openTypes = ["",1,3,"",2];
            // 扫码跳转的小程序没有检测权限,判断有没有开启授权
            $componentAppids = ["","wxa755405206410fd2","wxe7f72c27fd3683c6","","wxe7f72c27fd3683c6"];
            foreach ($miniapps as $miniapp) {
                $open_type = $openTypes[$miniapp->miniapp_type];
                $component_appid = $componentAppids[$miniapp->miniapp_type];
                // 获取小程序授权信息
                $miniappAuth = Miniappsauthorization::getCompMiniappAuth($miniapp->appid,$component_appid);
                if (empty($miniappAuth)) {
                    // 没有获取到小程序授权信息,更新检测状态
                    $this->unAuthorAppids[] = $miniapp->appid;
                } else {
                    // try {                            
                        $access_token = WechatopenService::getMiniProgramAccessToken($miniappAuth->component_appid,$miniapp->appid,$miniappAuth->authorizer_refresh_token);
                        //根据第三方token检测小程序状态
                        $visitStatus = WechatsService::getvisitstatus($access_token);
                        if($visitStatus["errcode"] == 0){
                            // 获取检测结果成功
                            // status:0、表示已暂停服务（包含主动暂停服务违规被暂停服务）,1、表示未暂停服务。
                            dump($visitStatus);
                            if($visitStatus["status"] == 0){
                                $message = "";
                                //更新小程序状态
                                Linkslistsminapps::updateLinksListMiniappDisable($miniapp->appid,5,2);
                                if (in_array($miniapp->type, [3,4,5])) {
                                    //公用二维码小程序
                                    if(in_array($miniapp->miniapp_type,[1,4]) && Redis::get("today_mini_times_".date('Ymd')) > 3){
                                        $platfromUseable = Linkslistsminapps::getPublicUseableMinappsBySecret();
                                    }else{
                                        $platfromUseable = Linkslistsminapps::getPublicUseableMinappsByscan();
                                    } 
                                    if(empty($platfromUseable)) $platfromUseable = Linkslistsminapps::getPublicUseableMinapps();
                                    if (empty($platfromUseable)) {
                                        $message = "二维码小程序暂停服务无备用";
                                    } else {
                                        //检测被切换小程序状态，是否可用
                                        $component_appid_b = $componentAppids[$platfromUseable->miniapp_type];
                                        $miniappAuth_b = Miniappsauthorization::getCompMiniappAuth($platfromUseable->appid,$component_appid_b);
                                        $access_token_b = WechatopenService::getMiniProgramAccessToken($miniappAuth_b->component_appid,$platfromUseable->appid,$miniappAuth_b->authorizer_refresh_token);
                                        //根据第三方token检测小程序状态
                                        $visitStatus_b = WechatsService::getvisitstatus($access_token_b);
                                        if($visitStatus_b["status"] == 0){
                                            Linkslistsminapps::updateLinksListMiniappDisable($platfromUseable->appid,5,2);
                                            if(in_array($platfromUseable->miniapp_type,[1,4]) && Redis::get("today_mini_times_".date('Ymd')) > 3){
                                                $platfromUseable = Linkslistsminapps::getPublicUseableMinappsBySecret();
                                            }else{
                                                $platfromUseable = Linkslistsminapps::getPublicUseableMinappsByscan();
                                            } 
                                            if(empty($platfromUseable)) $platfromUseable = Linkslistsminapps::getPublicUseableMinapps();
                                            if (empty($platfromUseable)) {
                                                $message = "二维码小程序暂停服务无备用";
                                            }else{
                                                // 把小程序设为默认
                                                Linkslistsminapps::updatePublicLinksListsStatus($platfromUseable->id,3,$miniapp->type);
                                                // 更新所有此类型链接的APPID
                                                Linkslists::updateLinksAppid($miniapp->appid,$platfromUseable->appid,$platfromUseable->original_id,$platfromUseable->miniapp_type);
                                                $message = "已切换二维码小程序".$platfromUseable->name;
                                                Cache::forget('public_miniapp_3');
                                            }
                                        }else{
                                            if(in_array($miniapp->miniapp_type,[1,4])){
                                                Redis::incr("today_mini_times_".date('Ymd'));
                                            }
                                            // 把小程序设为默认
                                            Linkslistsminapps::updatePublicLinksListsStatus($platfromUseable->id,3,$miniapp->type);
                                            // 更新所有此类型链接的APPID
                                            Linkslists::updateLinksAppid($miniapp->appid,$platfromUseable->appid,$platfromUseable->original_id,$platfromUseable->miniapp_type);
                                            $message = "已切换二维码小程序".$platfromUseable->name;
                                            Cache::forget('public_miniapp_3');
                                        }
                                    }
                                }elseif ($miniapp->type == 6) {
                                    //把已经会员未到期的链接更新成公用的二维码使用的小程序
                                    $defaultminiapp = Linkslistsminapps::getDefaultPublicMinapp();
                                    if(!empty($defaultminiapp)){
                                        Linkslists::updateFreeMemberLinksAppid($miniapp->appid,$defaultminiapp->appid,$defaultminiapp->original_id,$defaultminiapp->miniapp_type);
                                    }
                                    
                                    $platfromUseable = Linkslistsminapps::getPublicUseableMinapps();
                                    // 免费小程序被封
                                    if (empty($platfromUseable)) {
                                        $message = "免费小程序暂停服务无备用";
                                    } else {
                                        // 把小程序设为默认
                                        Linkslistsminapps::updatePublicLinksListsStatus($platfromUseable->id,3,$miniapp->type);
                                        Linkslists::updateLinksAppid($miniapp->appid,$platfromUseable->appid,$platfromUseable->original_id,$platfromUseable->miniapp_type);
                                        $message = "已切换免费小程序".$platfromUseable->name;
                                        Cache::forget('public_miniapp_6');
                                    }
                                }
                                //推送
                                $nowTime = date("Y-m-d H:i:s",time());
                                // 发送公众号消息推送
                                $paramas = [
                                    'first' => '',
                                    'keyword1' => $miniapp->name,
                                    'keyword2' => $message,
                                    'keyword3' => $nowTime,
                                    'remark' => '',
                                ];
                                // 开启公众号推
                                $wechatOpenid = "owYdF6lncu-z2DhgbTAMZqeXK_tY";
                                WechattmplmsgService::sendSingleTempleteMsg("q7AYyeTy8mo6SonXsMSA56pfkoy-LMioTgA1MCIJvVw",$wechatOpenid,"https://bab.moreqifu.cn/admin/miniapp/miniapp_list","","",$paramas);

                            } else {

                            }
                        } else {
                            if ($visitStatus["errcode"] == 61007) {
                                // 授权第三方没有api检测权限
                                $this->unAuthorAppids[] = $miniapp->appid;
                            }
                        }
                    // } catch (Exception $e) {
                    //     // 未获取到小程序token
                    //     $this->unAuthorAppids[] = $miniapp->appid;
                    //     // Log::info();
                    // }
                }
            }
        });
        if (!empty($this->unAuthorAppids)) {
            // 更新无法检测列表
            // DB::table("links_lists_minapps")->whereIn("appid",$this->unAuthorAppids)->update(["visitstatus" => 3]);
            Log::info($this->unAuthorAppids);
        }
    }
}
